package com.binguo.thirdPay.caoGenYaoPay;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.binguo.common.util.PriceUtil;
import com.binguo.model.wxapi.vo.CaoGenYaoPayCardVO;
import com.google.common.collect.Lists;
import org.omg.Messaging.SYNC_WITH_TRANSPORT;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yuritian
 * @Title: CaoGenYaoPay
 * @ProjectName binguoDevelop
 * @Description: TODO
 * @date 2019-10-1409:23
 */
@Service
public class CaoGenYaoPay {

    //测试URL
//    private String URL = "https://cscrm7.wuuxiang.com/crm7api/";
    //正式URL
    private String URL = "https://scrm.wuuxiang.com/crm7api/";
    //测试加密公钥
//    private String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDBgqqTw4oBp4EKI35K6VSUMqCogsropY1voAkHrBf6AZl4kb2TdG2TfKhTzBsPBtp/3wrTAlUHO6g1qHr/FaUVQc3U1gkf/XdWWcXr+2UEfq6OJt0KdNXcBGSA1zY7Q6ndWTOGjMtSdvbkC0VoFP4T6+AZRHwehpK52rr+aEVKNQIDAQAB";
    //正式加密公钥
    private String PUBLIC_KEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCFyrqI4Rp4XofofXLG8DHml8ESQUM5dM1SOWQCwCGcDxSYygHKqwFVTLPMiLoNJmpYAN30W9qmtBcgQIokOFg3ngcyHjQoLdc2hMGapyxyvITx62kkBrLgarsM0j6KtjxNf2T17MxRVnzfI4Mm6mddTl6HdZWhFj5tpMxoHold6wIDAQAB";

    private final String VERSION = "1.0.0";


    public static void main(String[] args) {
        CaoGenYaoPay caoGenYaoPay = new CaoGenYaoPay();
//        caoGenYaoPay.createPayCard("13588204717");
//        caoGenYaoPay.caoGenYaoPay(790001L,"1234",1.00);
//        caoGenYaoPay.getPayCard();
//        caoGenYaoPay.findCardNoByPhone("13588204717",1000001056L);
//        caoGenYaoPay.findCardNoByValue("15357810002",1000017001L,1000110774562L,1000039585L,2);
        caoGenYaoPay.findCardNoByValue("800033017",1000017001L,1000110774562L,1000039585L,1);
//        caoGenYaoPay.findBalanceByCardId(790001L,1000001056L);
//        caoGenYaoPay.findBalanceByCardId(10211905424L,1000017001L);
    }

    public JSONObject createPayCard(String phoneNum,
                                    String cardTypeId,
                                    Long comPanyId,
                                    String shopId,
                                    String terMinalId){
        JSONObject param = new JSONObject();
        param.put("companyId",comPanyId);
        param.put("shopId",shopId);
        param.put("terminalId",terMinalId);
        JSONObject cardInfo = new JSONObject();
        cardInfo.put("mobile",phoneNum);
        cardInfo.put("cardTypeId",cardTypeId);
        param.put("cardInfo",cardInfo);
        String sign = CaoGenYaoRSAUtil.encryptByPublicKey(param.toJSONString(),PUBLIC_KEY);
        return postRessultJson("api/posTrade/sellcardWithoutNo.do",sign,comPanyId);
    }

    /**
    　　* @Description: 根据手机号码查询到菜根谣系统中获取卡号
    　　* @param phoneNum 手机号码
    　　* @return JSONObject
    　　* @throws
    　　* @author 余敬
    　　* @date 2019-10-15 16:14
    　　*/
    public List<CaoGenYaoPayCardVO> findCardNoByValue(String searchTypeValue,
                                                      Long companyId,
                                                      Long cardTypeId,
                                                      Long shopId,
                                                      Integer searchType){
        JSONObject param = new JSONObject();
        param.put("companyId",companyId);
        param.put("searchTypeValue",searchTypeValue);
        param.put("searchType",searchType);
        param.put("cardTypeId",cardTypeId);
        param.put("shopId",shopId);
        String sign = CaoGenYaoRSAUtil.encryptByPublicKey(param.toJSONString(),PUBLIC_KEY);
        JSONObject ressultJson = getRessultJson("api/card/list.do",sign,companyId);
        String status = ressultJson.getString("status");
        String successStatus = "1";
        if (!status.equals(successStatus)){
            return null;
        }
        JSONArray list = ressultJson.getJSONObject("rpData").getJSONArray("list");
        if(list.size() == 0){
            return null;
        }
        JSONObject payCard;
        List<CaoGenYaoPayCardVO> cardNoList = new ArrayList<>();
        for (int i = 0;i< list.size();i++){
            payCard = list.getJSONObject(i);
            CaoGenYaoPayCardVO cardVO = new CaoGenYaoPayCardVO();
            cardVO.setCardId(payCard.getString("id"));
            cardVO.setCardNo(payCard.getString("number"));
            System.out.println(cardVO.getCardId() + "   " +cardVO.getCardNo());
            cardNoList.add(cardVO);
        }
        return cardNoList;
    }
    public Long findBalanceByCardId(Long cardId,
                                    Long companyId){

        JSONObject param = new JSONObject();
        param.put("companyId",companyId);
        param.put("cardId",cardId);
        String sign = CaoGenYaoRSAUtil.encryptByPublicKey(param.toJSONString(),PUBLIC_KEY);
        JSONObject ressultJson = getRessultJson("api/card/cardAccountDetail.do",sign,companyId);
        String status = ressultJson.getString("status");
        String successStatus = "1";
        if (!status.equals(successStatus)){
            return null;
        }
        JSONArray list = ressultJson.getJSONArray("rpData");
        JSONObject balanceJsonObject;
        String cardBalance = "0.00";
        for (int i= 0; i < list.size();i++){
            balanceJsonObject = list.getJSONObject(i);
            String balance = balanceJsonObject.getString("balance");
            cardBalance = getBalance(cardBalance,balance);
        }
        System.out.println(cardBalance);
        Long realBalance = PriceUtil.getRealPrice(cardBalance);

        return realBalance;
    }

    public JSONObject caoGenYaoPay(Long cardNo,
                                   String thirdTsCode,
                                   Double allMoney,
                                   Long comPanyId,
                                   Long shopId,
                                   Long terMinalId){
        JSONObject param = new JSONObject();
        param.put("companyId",comPanyId);
        param.put("shopId",shopId);
        param.put("terminalId",terMinalId);
        param.put("cardNo",cardNo);
        param.put("thirdTsCode",thirdTsCode);
        param.put("allMoney",allMoney);
        param.put("cardAllMoney",allMoney.toString());
        param.put("consumeMoney",allMoney.toString());
        param.put("consumeScore",0);
        String sign = CaoGenYaoRSAUtil.encryptByPublicKey(param.toJSONString(),PUBLIC_KEY);
        return postRessultJson("api/posTrade/consumeV1.do",sign,comPanyId);
    }

    private JSONObject getRessultJson(String method,String sign,Long comPanyId) {
        RestTemplate restTemplate = new RestTemplate();
        String getURL = URL+method+"?sign=" + sign + "&" + "productId=" + comPanyId + "&" + "version=" + VERSION;
        ResponseEntity<String> resp = restTemplate.getForEntity(getURL, String.class);
        String result = resp.getBody();
        System.out.println(result);
        return JSONObject.parseObject(result);
    }

    private JSONObject postRessultJson(String method,String sign,Long comPanyId){
        RestTemplate restTemplate = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.setAccept(Lists.newArrayList(MediaType.APPLICATION_JSON));
        JSONObject params = new JSONObject();
        params.put("productId",comPanyId);
        params.put("version",VERSION);
        params.put("sign",sign);
        HttpEntity<String> entity = new HttpEntity<String>(params.toJSONString(), headers);
        ResponseEntity<String> resp = restTemplate.postForEntity(URL+method, entity, String.class);
        String result = resp.getBody();
        System.out.println(result);
        return JSONObject.parseObject(result);
    }

    public String getBalance(String value1,
                             String value2){
        BigDecimal bignum1 = new BigDecimal(value1);
        BigDecimal bignum2 = new BigDecimal(value2);
        BigDecimal bignum3 = null;

        //加法
        bignum3 =  bignum1.add(bignum2);
        System.out.println("和 是：" + bignum3);
        return bignum3.toString();
   }

}
